package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    private final CategoryBrandService categoryBrandService;

    public BrandServiceImpl(CategoryBrandService categoryBrandService) {
        this.categoryBrandService = categoryBrandService;
    }

    @Override
    public PageDTO<BrandDTO> queryBrandByPage(String key, Integer page, Integer rows) {
        // 1.分页信息的健壮性处理
        page = Math.min(page, 100);// 页数不能超过100
        rows = Math.max(rows, 5); // 每行不小于5
        // 2.判断key是否存在,apache 的 字符串工具类 common-lang3
        boolean isKeyExists = StringUtils.isNotBlank(key);
        // 3.如果key存在，添加like和eq的查询条件，否则不添加
        // 第一个入参boolean condition表示该条件是否加入最后生成的sql中
        Page<Brand> info = query()
                .like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(new Page<>(page, rows));
        // 4.封装结果
        List<Brand> list = info.getRecords();
        List<BrandDTO> dtoList = BrandDTO.convertEntityList(list);

        return new PageDTO<>(info.getTotal(), info.getPages(), dtoList);
    }

    @Override
    @Transactional
    public void saveBrand(BrandDTO brandDTO) {
        // 1.把DTO转PO
        Brand brand = brandDTO.toEntity(Brand.class);
        // 2.新增品牌
        save(brand);
        // 3.新增中间表
        /*// 3.1.获取分类id集合
        List<Long> categoryIds = brandDTO.getCategoryIds();
        // 3.2.把品牌和分类id的集合，组装变成中间表对象集合
        List<CategoryBrand> cbList = new ArrayList<>();
        for (Long categoryId : categoryIds) {
            // 封装中间表对象
            CategoryBrand cb = CategoryBrand.of(categoryId, brand.getId());
            // 中间表对象存入集合
            cbList.add(cb);
        }*/
        List<CategoryBrand> cbList = brandDTO.getCategoryIds()
                .stream()
                .map(categoryId -> CategoryBrand.of(categoryId, brand.getId()))
                .collect(Collectors.toList());
        // 3.3.批量新增
        categoryBrandService.saveBatch(cbList);
    }

    @Override
    public List<BrandDTO> queryBrandByCategory(Long id) {
        // 查询自定义sql，根据分类id查询品牌
        List<Brand> list = getBaseMapper().queryByCategory(id);
        // 转换DTO
        return BrandDTO.convertEntityList(list);
    }
}